package listeners;

import gui.GuiController;

import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;

public class SongTableListener implements MouseListener{
	
	private GuiController gc;
	
	public SongTableListener(GuiController gc){
		this.gc = gc;
	}

	

	@Override
	public void mouseClicked(MouseEvent e) {
		
		JTable target = (JTable)e.getSource();
		//int row = target.getSelectedRow();
		// get the coordinates of the mouse click
					Point p = e.getPoint();
		 
					// get the row index that contains that coordinate
					int row = target.rowAtPoint(p);
		 
					// Get the ListSelectionModel of the JTable
					ListSelectionModel model = target.getSelectionModel();
		 
					// set the selected interval of rows. Using the "rowNumber"
					// variable for the beginning and end selects only that one row.
					model.setSelectionInterval( row, row );
		if(e.getClickCount() == 2){
			
			
			System.out.println("Double clicked on row " + row);
			gc.playSong(row);
		}
		if(e.isMetaDown()){
			doPop(e, row);
		}
		
		

	}

	private void doPop(MouseEvent e, int row){
        PopUpDemo menu = new PopUpDemo(row);
        menu.show(e.getComponent(), e.getX(), e.getY());
    }



	@Override
	public void mouseEntered(MouseEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseExited(MouseEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mousePressed(MouseEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseReleased(MouseEvent arg0) {
		// TODO Auto-generated method stub

	}
	
	class PopUpDemo extends JPopupMenu{
		JMenuItem deleteItem;
		public PopUpDemo(final int row){
			deleteItem = new JMenuItem("Delete");
			deleteItem.addActionListener(new ActionListener() {
				
				@Override
				public void actionPerformed(ActionEvent arg0) {
					gc.delete(row);
					
				}
			});
			add(deleteItem);
		}
		
	}

}
